import { _decorator, Component, SpriteAtlas, Prefab, ProgressBar, Label, Node, JsonAsset, Asset } from "cc";
import { SCENE_NAME } from "../Constants";
import { TaskManager } from "../utils/TaskManager";
import { CocosUtils } from "../utils/CocosUtils";
import { DataManager } from "../manager/DataManager";
const { ccclass, property } = _decorator;


@ccclass("StartManager")
export class StartManager extends Component {

    @property(ProgressBar)
    public progressBar: ProgressBar = null;

    @property(Label)
    public tipsLabel: Label = null;

    public async onLoad(): Promise<void> {
        if (DataManager.instance.isAssetsLoaded) {
            this.progressBar.node.active = false;
            this.tipsLabel.node.active = true;
            this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        } else {
            this.progressBar.node.active = true;
            this.tipsLabel.node.active = false;


            const taskManager = new TaskManager();
            const assetConfig: { path: string, weight: number, type: typeof Asset }[] = [
                {
                    path: "texture",
                    weight: 5,
                    type: SpriteAtlas
                },
                {
                    path: "prefab",
                    weight: 3,
                    type: Prefab
                },
                {
                    path: "config",
                    weight: 2,
                    type: JsonAsset
                }
            ];
            for (const asset of assetConfig) {
                taskManager.add(asset.path, asset.weight, async (task, onProgress) => {

                    await CocosUtils.loadAssetDir(asset.path, asset.type, (progress) => {
                        onProgress(progress);
                    });
                    return true;
                })
            }
            await taskManager.runParallel((progress) => {
                progress > this.progressBar.progress && (this.progressBar.progress = progress);
            }, this);
            DataManager.instance.isAssetsLoaded = true;
            this.startBattle();
        }
    }

    public onDisable(): void {
        this.node.targetOff(this);
    }

    private onTouchEnd(): void {
        this.startBattle();
    }

    private async startBattle(): Promise<void> {
        await CocosUtils.loadScene(SCENE_NAME.BATTLE);
    }
}